package com.atguigu.gmall.service;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022-12-14 20:21
 */
@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送延迟消息的封装
     * @param exchange 交换机
     * @param routingKey 路由
     * @param message 消息
     * @param delayTime 延迟时间
     * @return
     */
    public boolean sendDelayMessage(String exchange, String routingKey, Object message, int delayTime) {
        // 创建封装消息对象
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        // 唯一标识id
        String correlationDataId = UUID.randomUUID().toString().replace("-", "");
        // 封装数据
        gmallCorrelationData.setId(correlationDataId);
        gmallCorrelationData.setMessage(message);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setDelayTime(delayTime);
        // 保存到redis中
        redisTemplate.opsForValue().set(correlationDataId, JSONObject.toJSONString(gmallCorrelationData),
                10, TimeUnit.MINUTES);
        // 发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, message, msg -> {
            msg.getMessageProperties().setDelay(delayTime * 1000);
            return msg;
        }, gmallCorrelationData);
        return true;
    }


    /**
     * 发送消息的封装
     * @param exchange 交换机
     * @param routingKey 路由
     * @param message 消息数据
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        // 创建封装消息对象
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        // 唯一标识id
        String correlationDataId = UUID.randomUUID().toString().replace("-", "");
        // 封装数据
        gmallCorrelationData.setId(correlationDataId);
        gmallCorrelationData.setMessage(message);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        // 保存到redis中
        redisTemplate.opsForValue().set(correlationDataId, JSONObject.toJSONString(gmallCorrelationData),
                10, TimeUnit.MINUTES);
        // 发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, message, gmallCorrelationData);
        // rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

}
